<template>
  <div class="app-container">
    <div class="statistics-container">
      <h2 class="page-title">订单统计</h2>
      
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="queryParams" :inline="true" class="filter-form">
          <el-form-item label="操作类型">
            <el-select v-model="queryParams.operationType" placeholder="全部" style="width: 120px;">
              <el-option label="全部" value="all"></el-option>
              <el-option label="微信支付" value="wechat"></el-option>
              <el-option label="支付宝支付" value="alipay"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 240px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 基础统计 -->
      <div class="statistics-section">
        <h3>基础统计</h3>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.successOrders || 0 }}</div>
                <div class="stat-label">支付订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.successAmount) }}</div>
                <div class="stat-label">订单金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.refundedOrders || 0 }}</div>
                <div class="stat-label">退款订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.refundedAmount) }}</div>
                <div class="stat-label">退款金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.pendingOrders || 0 }}</div>
                <div class="stat-label">待支付订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.pendingAmount) }}</div>
                <div class="stat-label">待支付金额</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-section">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>支付方式分布</span>
            </div>
            <div id="paymentMethodChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>订单趋势分析</span>
            </div>
            <div id="orderTrendChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 订单状态统计 -->
      <div class="statistics-section">
        <h3>订单状态统计</h3>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.successOrders || 0 }}</div>
                <div class="stat-label">支付成功订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.successAmount) }}</div>
                <div class="stat-label">支付成功金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.pendingOrders || 0 }}</div>
                <div class="stat-label">待支付订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.pendingAmount) }}</div>
                <div class="stat-label">待支付金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.closedOrders || 0 }}</div>
                <div class="stat-label">已关闭订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.closedAmount) }}</div>
                <div class="stat-label">已关闭金额</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 退款统计 -->
      <div class="statistics-section">
        <h3>退款统计</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.refundedOrders || 0 }}</div>
                <div class="stat-label">退款订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.refundedAmount) }}</div>
                <div class="stat-label">退款金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.actualRefundAmount) }}</div>
                <div class="stat-label">实际退款金额</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 支付失败订单统计 -->
      <div class="statistics-section">
        <h3>支付失败订单统计</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.failedOrders || 0 }}</div>
                <div class="stat-label">支付失败订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.failedAmount) }}</div>
                <div class="stat-label">支付失败金额</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 其他有用统计 -->
      <div class="statistics-section">
        <h3>其他有用统计</h3>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.wechatOrders || 0 }}</div>
                <div class="stat-label">微信订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.wechatAmount) }}</div>
                <div class="stat-label">微信金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ statisticsData.alipayOrders || 0 }}</div>
                <div class="stat-label">支付宝订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">¥{{ formatAmount(statisticsData.alipayAmount) }}</div>
                <div class="stat-label">支付宝金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ formatPercentage(statisticsData.paymentSuccessRate) }}%</div>
                <div class="stat-label">支付成功率</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-value">{{ formatPercentage(statisticsData.refundRate) }}%</div>
                <div class="stat-label">退款率</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { getOrderStatistics } from '@/api/payment'
import * as echarts from 'echarts'

export default {
  name: "OrderStatistics",
  data() {
    return {
      // 查询参数
      queryParams: {
        operationType: 'all',
        dimension: 'day'
      },
      // 日期范围
      dateRange: [],
      // 统计数据
      statisticsData: {},
      // 图表实例
      paymentMethodChart: null,
      orderTrendChart: null
    }
  },
  created() {
    // 设置默认日期范围（最近7天）
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(startDate.getDate() - 7)
    
    this.dateRange = [
      this.formatDate(startDate),
      this.formatDate(endDate)
    ]
    
    this.getStatisticsData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.paymentMethodChart) {
      this.paymentMethodChart.dispose()
    }
    if (this.orderTrendChart) {
      this.orderTrendChart.dispose()
    }
  },
  methods: {
    // 获取统计数据
    getStatisticsData() {
      const params = {
        dimension: this.queryParams.dimension,
        startDate: this.dateRange[0],
        endDate: this.dateRange[1]
      }
      
      getOrderStatistics(params).then(response => {
        if (response.code === 200) {
          this.statisticsData = response.data
          this.updateCharts()
        } else {
          this.$message.error('获取统计数据失败')
        }
      }).catch(error => {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
      })
    },
    
    // 查询按钮
    handleQuery() {
      this.getStatisticsData()
    },
    
    // 格式化金额
    formatAmount(amount) {
      if (!amount) return '0.00'
      return parseFloat(amount).toFixed(2)
    },
    
    // 格式化百分比
    formatPercentage(percentage) {
      if (!percentage) return '0.00'
      return parseFloat(percentage).toFixed(2)
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 初始化图表
    initCharts() {
      this.initPaymentMethodChart()
      this.initOrderTrendChart()
    },
    
    // 支付方式分布饼图
    initPaymentMethodChart() {
      const chartDom = document.getElementById('paymentMethodChart')
      if (!chartDom) return
      
      this.paymentMethodChart = echarts.init(chartDom)
      this.updatePaymentMethodChart()
    },
    
    // 订单趋势折线图
    initOrderTrendChart() {
      const chartDom = document.getElementById('orderTrendChart')
      if (!chartDom) return
      
      this.orderTrendChart = echarts.init(chartDom)
      this.updateOrderTrendChart()
    },
    
    // 更新支付方式分布图
    updatePaymentMethodChart() {
      if (!this.paymentMethodChart) return
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['微信支付', '支付宝支付']
        },
        series: [
          {
            name: '支付方式',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: [
              { 
                value: this.statisticsData.wechatOrders || 0, 
                name: '微信支付',
                itemStyle: { color: '#67C23A' }
              },
              { 
                value: this.statisticsData.alipayOrders || 0, 
                name: '支付宝支付',
                itemStyle: { color: '#409EFF' }
              }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      this.paymentMethodChart.setOption(option)
    },
    
    // 更新订单趋势图
    updateOrderTrendChart() {
      if (!this.orderTrendChart) return
      
      // 生成最近7天的日期数据
      const dates = []
      const orderData = []
      const amountData = []
      
      for (let i = 6; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        dates.push(this.formatDate(date))
        
        // 模拟数据，实际应该从API获取
        orderData.push(Math.floor(Math.random() * 10))
        amountData.push(Math.floor(Math.random() * 100) / 100)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['订单量', '订单金额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: [
          {
            type: 'value',
            name: '订单量',
            position: 'left'
          },
          {
            type: 'value',
            name: '金额(元)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '订单量',
            type: 'line',
            yAxisIndex: 0,
            data: orderData,
            itemStyle: { color: '#409EFF' },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(64, 158, 255, 0.3)'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                }]
              }
            }
          },
          {
            name: '订单金额',
            type: 'line',
            yAxisIndex: 1,
            data: amountData,
            itemStyle: { color: '#67C23A' }
          }
        ]
      }
      
      this.orderTrendChart.setOption(option)
    },
    
    // 更新所有图表
    updateCharts() {
      this.updatePaymentMethodChart()
      this.updateOrderTrendChart()
    }
  }
}
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.filter-form {
  margin: 0;
}

.statistics-section {
  margin-bottom: 30px;
}

.statistics-section h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #606266;
  font-weight: 600;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.chart-section {
  margin-top: 30px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-card >>> .el-card__header {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #495057;
}
</style>